package com.xinai.util;

import com.alibaba.fastjson.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;


@SuppressWarnings({ "rawtypes", "unchecked" })
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
        if (object instanceof Map) {
        JSONObject json = new JSONObject();
        Map map = (Map) object;
        for (Object key : map.keySet()) {
        json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
        } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable)object)) {
        json.put(value);
        }
        return json;
        } else {
        return object;
        }
        }

        public static boolean isEmptyObject(JSONObject object) {
        return object.names() ==null;
        }

        public static Map<String, Object> getMap(JSONObject object, String key)throws JSONException {
        return toMap(object.getJSONObject(key));
        }


        public static Map<String, Object> toMap(JSONObject object)throws JSONException {

        Map<String,Object> map = new HashMap();
        Iterator keys = object.keys();
        while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
        }
        return map;
        }


public static List toList(JSONArray array) throws JSONException {
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++) {
        list.add(fromJson(array.get(i)));
        }
        return list;
        }

        private static Object fromJson(Object json)throws JSONException {
        if (json == JSONObject.NULL) {
        return null;
        } else if (json instanceof JSONObject) {
        return toMap((JSONObject) json);
        } else if (json instanceof JSONArray) {
        return toList((JSONArray) json);
        } else {
        return json;
        }
        }

//String 转 List<Map<String, Object>>
        public static List<Map<String, Object>> toListMap(String json){
                List<Object> list = JSON.parseArray(json);

                List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>();
                for (Object object : list){
                        Map<String,Object> ageMap = new HashMap<String,Object>();
                        Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map
        /*for (Entry<String, Object> entry : ret.entrySet()) {
            ageMap.put(entry.getKey());
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            listw.add(ageMap);  //添加到list集合  成为 list<map<String,Object>> 集合
        }  */
                        listw.add(ret);
                }
                return listw;

        }





        }


